/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Games;

import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;

/**
 * @author Brandon
 */
public class BoardCanvas extends Canvas {
    
    private static int cellSize = 0;
    private int rows;
    private int cols;
    public static final int EMPTY = 2;
    private int rectX = 0;
    private int rectY = 0;
    
    private GamesModel gamesModel;
    private GamesController gamesController;
    
    public BoardCanvas(int width,int height,int cols, int rows, GamesModel gamesModel,GamesController gamesController) {
    	setBackground(Color.WHITE);
    	this.setSize(width,height);
        this.rows = rows;
        this.cols = cols;
        
        this.gamesController = gamesController;
        this.gamesModel = gamesModel;
        this.gamesModel.getBoard().clearBoard();
        init();
    }
    
    void init() {
        if(this.getWidth() > this.getHeight())
            cellSize = this.getHeight()/cols;
        else
            cellSize = this.getWidth()/rows;
        this.addMouseListener(gamesController);
        this.addMouseMotionListener(gamesController);
    }
    
    public void drawBoard(Graphics g) {
        for(int i = 0; i <= cols; i++) {
            g.drawLine(i*cellSize, 0, i*cellSize, rows*cellSize);
        }
        for(int i = 0; i <= rows; i++) {
            g.drawLine(0, i*cellSize, cols*cellSize, i*cellSize);
        }
        for(int col=0;col<gamesModel.getBoard().getWidth();col++) {
            for(int row=0;row<gamesModel.getBoard().getHeight();row++) {
                int val = gamesModel.getBoard().getFieldValue(col, row);
                if (val!=EMPTY)
                    GamesController.game.getGraphicPiece(val, col, row, getCellSize(), getCellSize()).draw(g);
            }
        }
    }
    
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        drawBoard(g2);
        g2.setColor(Color.BLUE);
        g2.setStroke(new BasicStroke(2));
        g2.drawRect(rectX, rectY, cellSize, cellSize);
        g2.setColor(Color.BLACK);
    }
    
    @Override
    public void repaint() {
        super.repaint();
    }
    
    public static int getCellSize() {
        return cellSize;
    }

    public void drawSelection(int x, int y) {
        rectX = x;
        rectY = y;
    }
}